package com.baseproject.helper;

import android.os.Looper;

import com.baseproject.util.LogUtils;

import java.util.concurrent.Executors;

import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by hp on 2017/8/3.
 */

public class ThreadHelper {

    public static Subscriber defaultSubscriber = new Subscriber<Object>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            LogUtils.logCatchedException(e);
        }

        @Override
        public void onNext(Object o) {
        }
    };

    public static Observable doInBackground(IBackgroundThreadTask backgroundThreadTask) {
        if (Looper.myLooper() == Looper.getMainLooper()) {//当前在主线程才新开子线程
            return rx.Observable.create(new rx.Observable.OnSubscribe<Object>() {
                @Override
                public void call(Subscriber<? super Object> subscriber) {
                    subscriber.onNext(backgroundThreadTask.backgroundCall());
                }
            })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());

        } else {
            return rx.Observable.create(new rx.Observable.OnSubscribe<Object>() {
                @Override
                public void call(Subscriber<? super Object> subscriber) {
                    subscriber.onNext(backgroundThreadTask.backgroundCall());
                }
            })
                    .subscribeOn(Schedulers.immediate())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    }


    public static Scheduler getNamedScheduler(String name) {
        return Schedulers.from(Executors.newCachedThreadPool(r -> new Thread(r, name)));
    }

    public static void threadInfo(String caller) {
        System.out.println(caller + " => " + Thread.currentThread().getName());
    }

}
